package com.cos.hospital.ui.record;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.helper.MyOnFreshListener;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.ImageBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.TemplateListBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.UKeyboard;
import com.cos.hospital.tool.USpeech;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.tool.glide.UGlide;
import com.cos.hospital.tool.takephoto.GetPhotoActivity;
import com.cos.hospital.ui.record.adapter.AdapterTemplate;
import com.cos.hospital.widget.MyDividerDecoration;
import com.google.gson.JsonObject;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.jude.utils.JUtils;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * @Description: 所以病历编辑他们爹
 * @Author: Kosmos
 * @Date: 2018年09月23日 15:35
 * @Email: KosmoSakura@foxmail.com
 */
public abstract class RecordBaseActivity extends GetPhotoActivity {
    protected final int StateON = 1;//1：当前:
    protected final int StateOFF = 2;//2：未选中
    protected final int StateNone = 3;//3：不可点击
    protected final int FunVoice = 1;//语音
    protected final int FunTemplate = 2;//模板
    protected final int FunFormula = 3;//公式
    protected final int FunTakephoto = 4;//拍照
    @BindView(R.id.rec_info_name)
    protected TextView tInfoName;
    @BindView(R.id.rec_info_sex)
    protected TextView tInfoSex;
    @BindView(R.id.rec_info_age)
    protected TextView tInfoAge;
    @BindView(R.id.rec_info_time)
    protected TextView tInfoTime;
    @BindView(R.id.rec_info_cardid)
    protected TextView tInfoCardId;
    @BindView(R.id.rec_info_doctor)
    protected TextView tInfodoctor;
    @BindView(R.id.rec_edt_main)
    protected EditText edtMain;
    @BindView(R.id.rec_edit_fun_vocal_i)
    protected ImageView iVocalBtn;
    @BindView(R.id.rec_edit_fun_vocal_t)
    protected TextView iVocalT;
    @BindView(R.id.rec_edit_fun_waves_i)
    protected ImageView iVocalWaves;
    @BindView(R.id.rec_edit_fun_waves_lay)
    protected View iVocalWavesLay;
    @BindView(R.id.rec_edit_voice)
    protected TextView tVoice;
    @BindView(R.id.rec_edit_template)
    protected TextView tTemplate;
    @BindView(R.id.rec_edit_formula)
    protected TextView tFormula;
    @BindView(R.id.rec_edit_takephoto)
    protected TextView tTakephoto;
    @BindView(R.id.rec_edit_fun_lay)
    protected View layFun;//功能区视图总开关
    @BindView(R.id.rec_edit_fun_speed_lay)
    protected View laySpeed;//语音视图
    @BindView(R.id.rec_edit_fun_template_lay)
    protected View layTemplate;//模板视图
    @BindView(R.id.rec_edit_fun_formula_lay)
    protected View layFormula;//公式视图
    @BindView(R.id.rec_edit_fun_photo_lay)
    protected View layPhoto;//公式视图
    @BindView(R.id.rc_template)
    protected RecyclerView rvTemplate;
    protected int fldEleID;//编辑类型
    protected int templateType;//模版类型
    protected int fldDoctorId;//医生ID
    protected int fldPatientId;//患者ID
    protected int fldMedicalHistoryId;//病历ID
    protected int fldTreatmentState = -1;//患者治疗状态，0：无状态，1：治疗中，2：治疗完
    protected int eId;//病例 元素ID
    protected int treatmentNumber;//剩余针灸次数
    protected ArrayList<ImageBean> imageBeanList;
    @BindView(R.id.springView)
    protected SpringView spv;
    protected boolean firstTimeToGetTemplateList = true;//是否第一次获取元素模板
    protected String fldPatientName;
    private List<TemplateListBean.ItemsBean> listTemplate;
    private AdapterTemplate adapterTemplate;
    private int indexTemplate;
    private RecognizerListener recognizerListener;

    /**
     * @param state 状态
     * @apiNote :
     * int FunVoice = 1;//语音
     * int FunTemplate = 2;//模板
     * int FunFormula = 3;//公式
     * int FunTakephoto = 4;//拍照
     */
    protected abstract void onFunctionBtnClick(int state);

    /**
     * @param result 捕获到的语音文字
     */
    protected abstract void onSpeakBack(String result);

    /**
     * 点击【点击说话】按钮
     */
    protected void onSpeakClick() {
    }

    /**
     * 隐藏有所输入区域
     */
    protected void hideInputAll() {
    }

    /**
     * @param content 模板被点击时返回的内容
     */
    protected abstract void onTemplateSelect(String content);

    protected abstract void initData();

    @Override
    protected void init() {
        recognizerListener = new MyRecognizerListener();
        Intent intent = getIntent();
        eId = intent.getIntExtra(Code.SP.ID, 0);
        fldEleID = intent.getIntExtra(Code.SP.FLDELEID, RecordCode.Type.ChiefDescribe);
        templateType = fldEleID;
        String content = intent.getStringExtra(Code.SP.CONTENT);
        imageBeanList = intent.getParcelableArrayListExtra(Code.SP.IMAGEBEANLIST);
        fldTreatmentState = intent.getIntExtra(Code.SP.FLDTREATMENTSTATE, -1);
        fldMedicalHistoryId = intent.getIntExtra(Code.SP.FLDMEDICALHISTORYID, 0);
        fldDoctorId = intent.getIntExtra(Code.SP.FLDDOCTORID, 0);
        fldPatientId = intent.getIntExtra(Code.SP.FLDPATIENTID, 0);
        String fldName = intent.getStringExtra(Code.SP.FLDNAME);
        int fldSex = intent.getIntExtra(Code.SP.FLDSEX, 0);
        int fldAge = intent.getIntExtra(Code.SP.FLDAGE, 0);
        String fldCreateTime = intent.getStringExtra(Code.SP.FLDCREATETIME);
        String fldMedicalNum = intent.getStringExtra(Code.SP.FLDMEDICALNUM);
        String fldDoctorName = intent.getStringExtra(Code.SP.FLDDOCTORNAME);
        treatmentNumber = intent.getIntExtra(Code.SP.TREATMENTNUMBER, 0);
        showInfo(fldName, fldSex, fldAge, fldCreateTime, fldMedicalNum, fldDoctorName, content);
        initData();
        UKeyboard.SoftHideKeyBoardUtil.assistActivity(this);
        USpeech.getInstance().init(this);
        UGlide.loadImage(context, R.mipmap.ic_waves, iVocalWaves);
        checkVocalStateUI(false);
    }

    protected void showInfo(String fldName, int fldSex, int fldAge, String fldCreateTime, String fldMedicalNum, String fldDoctorName,
                            String content) {
        fldPatientName = fldName;
        tInfoName.setText(fldName);
        if (fldSex == 0) {
            tInfoSex.setText("女");
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_female);
            tInfoSex.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        } else {
            tInfoSex.setText("男");
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_male);
            tInfoSex.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        }
        tInfoAge.setText(fldAge + "岁");
        tInfoTime.setText(UDate.strToStrSafety(fldCreateTime, "yyyy-MM-dd"));
        tInfoCardId.setText("卡号：" + fldMedicalNum);
        tInfodoctor.setText("医师：" + fldDoctorName);
        if (fldEleID != RecordCode.Type.AcupunctureRecord) {
            edtMain.setText(content);
        }
    }

    /**
     * @apiNote 模板列表
     */
    protected void initTemplateAdapter() {
        listTemplate = new ArrayList<>();
        adapterTemplate = new AdapterTemplate(listTemplate);
        adapterTemplate.openLoadAnimation();//开启默认动画AlphaInAnimation
        rvTemplate.setLayoutManager(new LinearLayoutManager(context));
        adapterTemplate.setEmptyView(R.layout.lay_empty, rvTemplate);//设置当list中元素个数为0时显示的布局
        rvTemplate.addItemDecoration(new MyDividerDecoration(ContextCompat.getColor(context, R.color.white_bg), JUtils.dip2px(1)));
        rvTemplate.setAdapter(adapterTemplate);
        spv.setHeader(new DefaultHeader(context));
        spv.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                indexTemplate = 1;
                getTemplateData();
            }
        });
        adapterTemplate.setOnItemClickListener((adapter, view, position) -> {
            if (position >= 0 && position < listTemplate.size()) {
                TemplateListBean.ItemsBean templateBean = listTemplate.get(position);
                onTemplateSelect(UTxt.isNull(templateBean.getFldContent()));
                updateElementTemplate(templateBean.getId());
            }
        });
        adapterTemplate.setOnLoadMoreListener(() -> {
            indexTemplate++;
            getTemplateData();
        }, rvTemplate);
    }

    @OnClick({R.id.title_back, R.id.rec_info_root, R.id.title_root_lay,
        R.id.rec_edit_voice, R.id.rec_edit_template,
        R.id.rec_edit_formula, R.id.rec_edit_takephoto, R.id.rec_edit_fun_vocal_i})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                onBackPressed();
                break;
            case R.id.title_root_lay:
            case R.id.rec_info_root:
                hideInputAll();
                hideAllFun();//关闭功能区
                UKeyboard.with(this).hideForce(edtMain);
                break;
            case R.id.rec_edit_voice://语音:
                if (StateNone == (int) view.getTag()) {
                    showNotice("当前模块不支持该项编辑");
                } else {
                    changeBtns(tVoice, tTemplate, tFormula, tTakephoto);
                    showFunOne(laySpeed, layTemplate, layFormula, layPhoto);
                    onFunctionBtnClick(FunVoice);
                }
                break;
            case R.id.rec_edit_template://模板:
                if (StateNone == (int) view.getTag()) {
                    showNotice("当前模块不支持该项编辑");
                } else {
                    changeBtns(tTemplate, tVoice, tFormula, tTakephoto);
                    showFunOne(layTemplate, laySpeed, layFormula, layPhoto);
                    onFunctionBtnClick(FunTemplate);
                }
                break;
            case R.id.rec_edit_formula://公式:
                if (StateNone == (int) view.getTag()) {
                    showNotice("当前模块不支持该项编辑");
                } else {
                    changeBtns(tFormula, tTemplate, tVoice, tTakephoto);
                    showFunOne(layFormula, laySpeed, layTemplate, layPhoto);
                    onFunctionBtnClick(FunFormula);
                }
                break;
            case R.id.rec_edit_takephoto://拍照:
                if (StateNone == (int) view.getTag()) {
                    showNotice("当前模块不支持该项编辑");
                } else {
                    onFunctionBtnClick(FunTakephoto);
                }
                break;
            case R.id.rec_edit_fun_vocal_i://语音:
                onSpeakClick();
                if (!iVocalBtn.isSelected()) {
                    toSpeed();
                }
                break;
        }
    }

    /**
     * 更新模板使用次数
     */
    protected void updateElementTemplate(int id) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", id);
        UHttp.start(getServes().updateElementTemplate(jsonObject), "更新模板使用次数", new HttpMsgListener<JsonObject>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
            }

            @Override
            public void onSuccess(JsonObject dto) {
            }
        });
    }

    /**
     * 获取模板数据
     */
    protected void getTemplateData() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldEleID", templateType);
        jsonObject.addProperty("pageIndex", indexTemplate);
        jsonObject.addProperty("pageSize", 6);
        UHttp.start(getServes().getElementTemplate(jsonObject), "查询元素模板", new HttpMsgListener<ResultBean<TemplateListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                spv.onFinishFreshAndLoadDelay();
            }

            @Override
            public void onSuccess(ResultBean<TemplateListBean> dto) {
                if (dto.isSuccess()) {
                    TemplateListBean resultBean = dto.getResult();
                    if (resultBean != null) {
                        int pageIndex = resultBean.getPageIndex();
                        int pageSize = resultBean.getPageSize();
                        int recordCount = resultBean.getRecordCount();
                        if (pageIndex == 1) {
                            listTemplate.clear();
                            adapterTemplate.notifyDataSetChanged();
                        }
                        List<TemplateListBean.ItemsBean> itemsBeanList = resultBean.getItems();
                        if (itemsBeanList != null && itemsBeanList.size() != 0) {
                            listTemplate.addAll(itemsBeanList);
                        }
                        int totalPageCount = MyUtil.getInstance().getTotalPageCount(pageSize, recordCount);
                        if (totalPageCount <= pageIndex) {
                            adapterTemplate.loadMoreEnd();
                        } else {
                            adapterTemplate.loadMoreComplete();
                        }
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * @param open true为目标状态
     * @apiNote 修改语音按钮样式
     */
    private void checkVocalStateUI(boolean open) {
        if (open) {
            iVocalBtn.setSelected(true);
            iVocalWavesLay.setVisibility(View.VISIBLE);
            iVocalT.setText(R.string.vocal_on_say_please);
        } else {
            iVocalBtn.setSelected(false);
            iVocalT.setText(R.string.vocal_off_touch_please);
            iVocalWavesLay.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * @apiNote 开始说话
     */
    protected void toSpeed() {
        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.RECORD_AUDIO)) {
            Disposable subscribe = rxPermissions.request(Manifest.permission.RECORD_AUDIO)
                .subscribe(granted -> {
                    if (granted) {
                        startListening();
                    } else {
                        MyUtil.getInstance().toSetting(context, "你已拒绝获取录制音频权限，为保证你能正常使用语音输入功能，请开启该权限。", 10, false);
                    }
                });
            addEvent(subscribe);
        } else {
            startListening();
        }
    }

    private void startListening() {
        USpeech.getInstance().startListening(recognizerListener);
    }

    /**
     * @apiNote 修改按钮样式
     */
    protected void changeBtnState(TextView textView, int state) {
        switch (state) {
            case StateON://1：当前:
                textView.setBackgroundResource(R.drawable.rect_green);
                textView.setTextColor(ContextCompat.getColor(context, R.color.white));
                textView.setTag(StateON);
                break;
            case StateOFF://2：未选中
                textView.setBackgroundResource(R.drawable.rect_rim_gray);
                textView.setTextColor(ContextCompat.getColor(context, R.color.black_txt));
                textView.setTag(StateOFF);
                break;
            case StateNone://3：不可点击
                textView.setBackgroundResource(R.drawable.rect_rim_gray);
                textView.setTextColor(ContextCompat.getColor(context, R.color.gray_light));
                textView.setTag(StateNone);
                break;
        }
    }

    /**
     * @apiNote 修改按钮样式
     */
    private void changeBtns(TextView... tvs) {
        for (int i = 0; i < tvs.length; i++) {
            if (i == 0) {
                changeBtnState(tvs[i], StateON);
            } else {
                if (StateNone != (int) tvs[i].getTag()) {
                    changeBtnState(tvs[i], StateOFF);
                }
            }
        }
    }

    /**
     * @apiNote 显示某一个功能区域的布局
     */
    protected void showFunOne(View... shows) {
        UKeyboard.with(this).hideForce(edtMain);
        edtMain.postDelayed(() -> {
            layFun.setVisibility(View.VISIBLE);
            for (int i = 0; i < shows.length; i++) {
                if (i == 0) {
                    shows[i].setVisibility(View.VISIBLE);
                } else {
                    shows[i].setVisibility(View.GONE);
                }
            }
        }, 400);
    }

    /**
     * @apiNote 隐藏全部功能区
     */
    protected void hideAllFun() {
        layFun.setVisibility(View.GONE);
        laySpeed.setVisibility(View.GONE);
        layTemplate.setVisibility(View.GONE);
        layFormula.setVisibility(View.GONE);
        layPhoto.setVisibility(View.GONE);
        if (StateNone != (int) tFormula.getTag()) {
            changeBtnState(tFormula, StateOFF);
        }
        if (StateNone != (int) tTemplate.getTag()) {
            changeBtnState(tTemplate, StateOFF);
        }
        if (StateNone != (int) tVoice.getTag()) {
            changeBtnState(tVoice, StateOFF);
        }
        if (StateNone != (int) tTakephoto.getTag()) {
            changeBtnState(tTakephoto, StateOFF);
        }
    }

    @Override
    public void onBackPressed() {
        UKeyboard keyboard = UKeyboard.with(this);
        if (keyboard.isKeyboardShow()) {
            keyboard.hideForce(edtMain);
        } else if (layFun.isShown()) {
            hideAllFun();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void getPhotoSuccess(File file) {
    }

    private class MyRecognizerListener implements RecognizerListener {

        @Override
        public void onVolumeChanged(int volume, byte[] bytes) {
        }

        @Override
        public void onBeginOfSpeech() {
            checkVocalStateUI(true);
        }

        @Override
        public void onEndOfSpeech() {
            checkVocalStateUI(false);
        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) {
            String parseIatResult = USpeech.getInstance().parseIatResult(recognizerResult);
            if (parseIatResult == null) {
                showNotice("声音太小,没听清楚");
            } else {
                onSpeakBack(parseIatResult);
            }
        }

        @Override
        public void onError(SpeechError speechError) {
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {
        }
    }
}
